import axios from 'axios';
import { Card } from '../../types';

const API_BASE = '/api/cards';

export async function fetchCards(notebookId?: string): Promise<Card[]> {
  const params = notebookId ? { notebook_id: notebookId } : {};
  const res = await axios.get(API_BASE, { params });
  return res.data.map((card: any) => ({
    ...card,
    createdAt: new Date(card.created_at),
    nextReview: new Date(card.next_review),
    easeFactor: card.ease_factor,
    notebookId: card.notebook_id
  }));
}

export async function createCard(card: Omit<Card, 'id' | 'createdAt'>): Promise<Card> {
  const res = await axios.post(API_BASE, {
    notebook_id: card.notebook_id,
    title: card.title,
    content: card.content
  });
  
  return {
    ...res.data,
    createdAt: new Date(res.data.created_at),
    nextReview: new Date(res.data.next_review),
    easeFactor: res.data.ease_factor,
    notebookId: res.data.notebook_id
  };
}

export async function updateCard(card: Card): Promise<Card> {
  const res = await axios.put(`${API_BASE}/${card.id}`, {
    title: card.title,
    content: card.content
  });
  
  return {
    ...res.data,
    createdAt: new Date(res.data.created_at),
    nextReview: new Date(res.data.next_review),
    easeFactor: res.data.ease_factor,
    notebookId: res.data.notebook_id
  };
}

export async function deleteCard(id: string): Promise<Card> {
  const res = await axios.delete(`${API_BASE}/${id}`);
  return {
    ...res.data,
    createdAt: new Date(res.data.created_at),
    nextReview: new Date(res.data.next_review),
    easeFactor: res.data.ease_factor,
    notebookId: res.data.notebook_id
  };
} 